package ysq.xyg.wxapi.dao.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.imm.model.v20170906.DetectQRCodesRequest;
import com.aliyuncs.imm.model.v20170906.DetectQRCodesResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.baidu.aip.ocr.AipOcr;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import ysq.xyg.base.extend.oss.AliyunCloudStorageService;
import ysq.xyg.base.util.*;
import ysq.xyg.web.model.po.WebAccount;
import ysq.xyg.web.model.po.WebMember;
import ysq.xyg.web.service.WebMemberService;
import ysq.xyg.wxapi.api.WxApi;
import ysq.xyg.wxapi.api.WxApiClient;
import ysq.xyg.wxapi.api.WxMemoryCacheClient;
import ysq.xyg.wxapi.dao.WxDao;
import ysq.xyg.wxapi.model.base.MsgRequest;
import ysq.xyg.wxapi.model.base.MsgText;
import ysq.xyg.wxapi.model.base.User;
import ysq.xyg.wxapi.util.MsgXmlUtil;
import ysq.xyg.wxapi.util.WxMessageBuilder;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2017/6/23 0023.
 */
@Slf4j
@Repository("wxDao")
public class WxDaoImpl implements WxDao {
    AipOcr client = AipSingleton.getAipOcrInstance();
    @Resource
    private AliyunCloudStorageService aliyunCloudStorageService;
    @Autowired
    private WebMemberService webMemberService;

    /**
     * 文本消息处理
     * */
    @Override
    public String msgResponseText(MsgRequest msgRequest, WebAccount webAccount){
        String content = msgRequest.getContent();
        MsgText msgText = new MsgText();
        if(StrUtil.isNotEmpty(content)){
            WebMember webMember=acceptMemberId(msgRequest.getFromUserName());
            if(webMember==null){
                msgText.setContent("信息错误");
                return MsgXmlUtil.textToXml(WxMessageBuilder.getMsgResponseText(msgRequest, msgText));
            }else if(StrUtil.isEmpty(webMember.getPhone())){
                WebAccount wxAccountInfo = WxMemoryCacheClient.getSingleWxAccountInfo();
                msgText.setContent("请先绑定信息。\n\n<a href=\"" + wxAccountInfo.getBaseUrl() + "/phone/bindUser?memberId=" + webMember.getId() + "\">立即绑定</a>\n");
                return MsgXmlUtil.textToXml(WxMessageBuilder.getMsgResponseText(msgRequest, msgText));
            }
            //文本消息
            String tmpContent = content.trim();
            String[] contents=tmpContent.split("#");
            if(contents.length!=2){
                msgText.setContent("内容输入错误，请按照规定格式输入\n卷码名称#卷码号");
                return MsgXmlUtil.textToXml(WxMessageBuilder.getMsgResponseText(msgRequest, msgText));
            }
            msgText.setContent(null);
            return MsgXmlUtil.textToXml(WxMessageBuilder.getMsgResponseText(msgRequest, msgText));
        }
        msgText.setContent("内容输入错误，请按照规定格式输入\n卷码名称#卷码号");
        return MsgXmlUtil.textToXml(WxMessageBuilder.getMsgResponseText(msgRequest, msgText));
    }
    /**
     * 图片消息处理
     * */
    @Override
    public String msgResponseImage(String realPath,MsgRequest msgRequest, WebAccount webAccount){
        MsgText msgText = new MsgText();
        WebMember webMember=acceptMemberId(msgRequest.getFromUserName());
        if(webMember==null){
            msgText.setContent("信息错误");
            return MsgXmlUtil.textToXml(WxMessageBuilder.getMsgResponseText(msgRequest, msgText));
        }else if(StrUtil.isEmpty(webMember.getPhone())){
            WebAccount wxAccountInfo = WxMemoryCacheClient.getSingleWxAccountInfo();
            msgText.setContent("请先绑定信息。\n\n<a href=\"" + wxAccountInfo.getBaseUrl() + "/phone/bindUser?memberId=" + webMember.getId() + "\">立即绑定</a>\n");
            return MsgXmlUtil.textToXml(WxMessageBuilder.getMsgResponseText(msgRequest, msgText));
        }

        Map<String, String> resultMap = WxApiClient.handleVoice(WxApiClient.getAccessToken(),msgRequest.getMediaId(),realPath);
        String url = resultMap.get("amrFileName");
        File file=new File(realPath+url);
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        String newFileName = cn.hutool.core.date.DateUtil.format(cn.hutool.core.date.DateUtil.date(), "yyyyMMddHHmmss") +
                BaseUtil.acceptRandom(BaseUtil.NUMBER_CONTENT, 6) + ".jpg";
        String pPath = aliyunCloudStorageService.upload(inputStream, newFileName);
        log.info("pPath is "+pPath);
        if(StrUtil.isEmpty(pPath)){
            msgText.setContent("图片上传OSS错误！");
            return MsgXmlUtil.textToXml(WxMessageBuilder.getMsgResponseText(msgRequest, msgText));
        }
        /***
         * 调用阿里云二维码识别
         */
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", ProProperties.getInstance().getAliyunAccessKeyId(), ProProperties.getInstance().getAliyunAccessKeySecret());
        IAcsClient alyClient = new DefaultAcsClient(profile);
        DetectQRCodesRequest request = new DetectQRCodesRequest();
        request.setProject(ProProperties.getInstance().getAliyunQrBucketName());
        // JSON数组
        com.alibaba.fastjson.JSONArray jsonArray = new com.alibaba.fastjson.JSONArray();
        jsonArray.add(pPath);
        request.setSrcUris(jsonArray.toJSONString());
        String s = "";
        String qrImage="";
        try {
            DetectQRCodesResponse response = alyClient.getAcsResponse(request);
            s = new Gson().toJson(response);
            log.info("upload s is "+s);
            com.alibaba.fastjson.JSONArray successDetails= JSON.parseObject(s).getJSONArray("successDetails");
            if(successDetails!=null&&successDetails.size()>0){
                com.alibaba.fastjson.JSONArray qRCodes= successDetails.getJSONObject(0).getJSONArray("qRCodes");
                if(qRCodes!=null&&qRCodes.size()>0){
                    qrImage=qRCodes.getJSONObject(0).getString("content");
                }
            }

            System.out.println(s);
        } catch (ClientException e) {
            log.info("ErrCode:" + e.getErrCode());
            log.info("ErrMsg:" + e.getErrMsg());
            log.info("RequestId:" + e.getRequestId());
        }
        if(StrUtil.isEmpty(qrImage)){
            msgText.setContent("图片错误，未识别出二维码！");
            return MsgXmlUtil.textToXml(WxMessageBuilder.getMsgResponseText(msgRequest, msgText));
        }

        JSONObject res = AipSingleton.acceptText(client,realPath+url);
        JSONArray wordsResult = res.getJSONArray("words_result");
        String result="";
        if(wordsResult!=null&&wordsResult.length()>0){
            for(int i=0;i<wordsResult.length();i++){
                String words = wordsResult.getJSONObject(i).getString("words");
                if(StrUtil.isNotEmpty(words)&&!(words.contains("#"))){
                    if(StrUtil.isEmpty(result)){
                        result=words;
                    }else{
                        result+="#"+words;
                    }
                }
            }
        }
        msgText.setContent(null);
        return MsgXmlUtil.textToXml(WxMessageBuilder.getMsgResponseText(msgRequest, msgText));
    }


    /**
     * 获取用户信息
     * @return
     */
    protected WebMember acceptMemberId(String openid){
        WebMember member=webMemberService.selectEntityByOpenid(openid);
        if(member == null){
            WebAccount webAccount=WxMemoryCacheClient.getSingleWxAccountInfo();
            User user= WxApi.selectUser(webAccount.getAccessToken(),openid);
            //将用户信息插入数据库
            member=new WebMember();
            int cardNo = webMemberService.selectMaxId();
            if (cardNo < BaseConstant.MEMBER_MIN_DEFAULT_ID) {
                cardNo = BaseConstant.MEMBER_MIN_DEFAULT_ID;
            } else {
                cardNo = cardNo + 1;
            }
            member.setCreditScore(100);
            member.setId(BaseUtil.uId());
            if(user!=null){
                member.setNickName(BaseUtil.encodeBase64String(user.getNickname()));
                member.setHeadImage(user.getHeadimgurl());
            }
            member.setCardNo(String.valueOf(cardNo));
            member.setOpenid(openid);
            member.setRemoveTag(BaseConstant.BASE_REMOVE_TAG_NORMAL);
            member.setCreateTime(new Date());
            member.setUpdateTime(new Date());
            member.setGrade("1");
            member.setMoney(0.0);
            int ids=webMemberService.insert(member);
            if(ids>0){
                return member;
            }
            return null;
        }else{
            //用户存在
            return member;
        }
    }
    public String accept(String type,String code,String money,String memberId){
        WebAccount wxAccountInfo = WxMemoryCacheClient.getSingleWxAccountInfo();

        if(StrUtil.isEmpty(memberId)){
            return "";
        }
        String t="权益："+type+"\r\n卷码："+code+"\n价格：￥"+money+"\n\n<a href=\""+wxAccountInfo.getBaseUrl()+"/phone/my?memberId="+memberId+"\">账号中心和权限管理</a>\n\n<a href=\""+wxAccountInfo.getBaseUrl()+"/phone/index?memberId="+memberId+"\">查看更多交易价格</a>\n\n上传后务必绑定回款账号！";
        return t;
    }
}
